package com.gitee.neuray.security.wb.ribs.biz;

import com.gitee.neuray.security.common.biz.BaseBiz;
import com.gitee.neuray.security.common.msg.ListRestResponse;
import com.gitee.neuray.security.common.msg.TableResultResponse;
import com.gitee.neuray.security.common.util.Query;
import com.gitee.neuray.security.common.util.UUIDUtils;
import com.gitee.neuray.security.wb.ribs.feign.StaffFeign;
import com.gitee.neuray.security.wb.ribs.mapper.*;
import com.gitee.neuray.security.wb.ribs.util.wechat.entity.AccessToken;
import com.gitee.neuray.security.wb.ribs.vo.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class RibsBiz extends BaseBiz<RibsMapper, RibsVo> {
  @Autowired private RibsMapper ribsMapper;
  @Autowired private ClfBiz clfBiz;
  @Autowired private JtfBiz jtfBiz;
  @Autowired private CyfBiz cyfBiz;
  @Autowired private QtfyBiz qtfyBiz;
  @Autowired private ClfMapper clfMapper;
  @Autowired private JtfMapper jtfMapper;
  @Autowired private CyfMapper cyfMapper;
  @Autowired private QtfyMapper qtfyMapper;
  @Autowired private ApproveRoleMapper approveRoleMapper;
  @Autowired private HistoryMapper historyMapper;
  @Autowired private WechatBiz wechatBiz;
  @Autowired private StaffFeign staffFeign;
  @Autowired private ApproveRoleBiz approveRoleBiz;
  /**
   * 分页获取信息
   *
   * @param query
   * @return
   */
  public TableResultResponse page(Query query) {
    Page<Object> result = PageHelper.startPage(query.getPageNo(), query.getPageSize());
    List<RibsVo> list = ribsMapper.page(query);
    return new TableResultResponse(
        result.getPageSize(), result.getPageNum(), result.getPages(), result.getTotal(), list);
  }
  /**
   * 根据条件查询，不分角色
   *
   * @param ribsVo
   * @return
   */
  public ListRestResponse<List<RibsVo>> approveByDetail(RibsVo ribsVo) {
    List<RibsVo> list = ribsMapper.approveByDetail(ribsVo);
    return new ListRestResponse<List<RibsVo>>("查询成功",list.size(),list);
  }
  /**
   * 导出无分页
   *
   * @param query
   * @return
   */
  public List<RibsVo> nopage(Query query) {
    return ribsMapper.page(query);
  }

  /**
   * 提交报销单
   *
   * @param ribsVo
   */
  public void commitBXD(RibsVo ribsVo,String bxdh,String userId) {

    String id = UUIDUtils.generateShortUuid();
    ribsVo.setId(id);
    if(!"".equals(ribsVo.getBxdh())&&ribsVo.getBxdh()!=null){
      Example example = new Example(RibsVo.class);
      Example.Criteria criteria = example.createCriteria();
      criteria.andEqualTo("bxdh",bxdh);
      ribsMapper.updateByExampleSelective(ribsVo,example);
    }else{
      ribsVo.setBxdh(bxdh);
      super.insertSelective(ribsVo);
    }
    System.out.println("STEP5-------------------------------------"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    //插入历史表
    //如果是经理特批的提交，则代表是部门负责人提交，则历史表里新增一条提交操作

    String staffId = ribsVo.getStaffId();
    ApproveRoleVo approveRoleVo = new ApproveRoleVo();
    approveRoleVo.setStaffId(staffId);
    List<ApproveRoleVo> list = approveRoleBiz.selectList(approveRoleVo);
    boolean flag = false;
    for(ApproveRoleVo role : list){
      if("1".equals(role.getRoleId())){
        flag = true;
        break;
      }
    }
    // 如果提交人有部门负责人角色，则新增一条提交。
    if(flag){
      RibsVo ribsVoCopy = new RibsVo();
      BeanUtils.copyProperties(ribsVo,ribsVoCopy);
      ribsVoCopy.setBxzt("2");
      ribsVo.setYj("同意");
      insertHistory(ribsVoCopy,null,userId);
    }
    /*if("3".equals(ribsVo.getBxzt()) && "2".equals(ribsVo.getTp())){
      RibsVo ribsVoCopy = new RibsVo();
      BeanUtils.copyProperties(ribsVo,ribsVoCopy);
      ribsVoCopy.setBxzt("2");
      ribsVo.setYj("同意");
      insertHistory(ribsVoCopy,null,userId);
    }*/
    insertHistory(ribsVo,null,userId);
    System.out.println("STEP6-------------------------------------"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

  }

  public String getIndex() {
    return ribsMapper.getIndex();
  }

  @Override
  protected String getPageName() {
    return null;
  }

  public Map<String,Object> queryDetail(RibsVo ribsVo){

    String bxdh = ribsVo.getBxdh();
    String staffId = ribsVo.getStaffId();

    Map<String,Object> ret = new HashMap<>();
    //差旅费
    if("1".equals(ribsVo.getBxlx())){
      ClfVo clfVo = new ClfVo();
      clfVo.setBxdh(bxdh);
      clfVo.setStaffId(staffId);
      List<ClfVo> clfVos = clfBiz.queryClf(clfVo);
      ret.put("data",clfVos);
      ret.put("type","clf");
    //餐饮费
    }else if("3".equals(ribsVo.getBxlx())){
      CyfVo cyfVo = new CyfVo();
      cyfVo.setBxdh(bxdh);
      cyfVo.setStaffId(staffId);
      List<CyfVo> cyfVos = cyfBiz.queryCyf(cyfVo);
      ret.put("data",cyfVos);
      ret.put("type","cyf");
    //市内交通费
    }else if("2".equals(ribsVo.getBxlx())){
      JtfVo jtfVo = new JtfVo();
      jtfVo.setBxdh(bxdh);
      jtfVo.setStaffId(staffId);
      List<JtfVo> jtfVos = jtfBiz.queryJtf(jtfVo);
      ret.put("data",jtfVos);
      ret.put("type","jtf");
    //其他费用
    }else if("5".equals(ribsVo.getBxlx())){
      QtVo qtVo = new QtVo();
      qtVo.setBxdh(bxdh);
      qtVo.setStaffId(staffId);
      List<QtVo> qtVos = qtfyBiz.queryQt(qtVo);
      ret.put("data",qtVos);
      ret.put("type","qtfy");
    }

    return ret;

  }

  public void approveRibs(RibsVo ribsVo,HttpServletRequest request){
    String staffId = request.getHeader("userId");
    String wxUserId = request.getHeader("wxUserId");
    String accessToken = request.getHeader("wxAccessToken");
    if(null != ribsVo.getId() && !"".equals(ribsVo.getId())){
      //如果报销意见为驳回，这设置为已驳回，直接return 0驳回 1同意
      if("0".equals(ribsVo.getBxyj())){
        //super.updateSelectiveById(ribsVo);
        String roleId = "";
        String bxztBefore = ribsVo.getBxzt();
        roleId = this.checkRole(bxztBefore);
        ribsVo.setBxzt("5");
        super.updateSelectiveById(ribsVo);
        this.updateDetailZt(ribsVo);

        ApproveRoleVo approveRoleVo = new ApproveRoleVo();
        approveRoleVo.setStaffId(staffId);
        //List<ApproveRoleVo> roleIds = approveRoleMapper.select(approveRoleVo);
        // String roleId = roleIds.get(0).getRoleId();
        insertHistory(ribsVo,roleId,staffId);
        //驳回发送消息
        this.sendWxMsg(ribsVo,ribsVo.getBxyj(),ribsVo.getStaffId(),staffId);
        //super.deleteById(ribsVo.getId());
        return;
      }

      ApproveRoleVo approveRoleVo = new ApproveRoleVo();
      approveRoleVo.setStaffId(staffId);
      //List<ApproveRoleVo> roleIds = approveRoleMapper.select(approveRoleVo);
      String roleId = "";
      String bxztBefore = ribsVo.getBxzt();
      roleId = this.checkRole(bxztBefore);
      //String roleId = roleIds.get(0).getRoleId();
      //1部门负责人审批
      if("1".equals(roleId)){
        //非特批 设置为复核
        if("0".equals(ribsVo.getTp())){
          ribsVo.setBxzt("4");
          //普通特批 设置为已初审
        }else if("1".equals(ribsVo.getTp())){
          ribsVo.setBxzt("3");
        }
      //2总经理审批 设置为已复审
        // 去掉总经理审批
      /*}else if("2".equals(roleId)){
        ribsVo.setBxzt("4");
      //3会计审核 设置为已复核*/
      }else if("3".equals(roleId)){
        ribsVo.setBxzt("6");
      //4财务总监审核 设置为已打款
      }else if("4".equals(roleId)){
        ribsVo.setBxzt("7");
      }
      this.sendWxMsg(ribsVo,ribsVo.getBxyj(),ribsVo.getStaffId(),staffId);

      /*ApproveRoleVo approveRoleVo = new ApproveRoleVo();
      approveRoleVo.setStaffId(ribsVo.getStaffId());
      List<ApproveRoleVo> roleIds = approveRoleMapper.select(approveRoleVo);

      //如果之前是已提交证明是 负责人审批
      if("2".equals(ribsVo.getBxzt())){
      //如果是已经初审
      }else if("3".equals(ribsVo.getBxzt())){
        //非特批 走财务复核
        if("0".equals(ribsVo.getTp())){
          ribsVo.setBxzt("6");
          //普通特批 走复审
        }else if("0".equals(ribsVo.getTp())){
          ribsVo.setBxzt("4");
        }
      //如果是已复审，走财务复核
      }else if("4".equals(ribsVo.getBxzt())){
        ribsVo.setBxzt("6");
      //如果是已复核，走财务打款
      }else if("6".equals(ribsVo.getBxzt())){
        ribsVo.setBxzt("7");
      }*/

      this.updateDetailZt(ribsVo);
      super.updateSelectiveById(ribsVo);

      //插入历史表
      insertHistory(ribsVo,roleId,staffId);
    }
  }

  public void updateDetailZt(RibsVo ribsVo){
    String bxdh = ribsVo.getBxdh();
    String bxlx = ribsVo.getBxlx();

    //报销类型 1、差旅费 2、市内交通费 3、餐饮费 4、公司借款
    if("1".equals(bxlx)){
      Example example = new Example(ClfVo.class);
      Example.Criteria criteria = example.createCriteria();
      criteria.andEqualTo("bxdh",bxdh);
      ClfVo clfVo = new ClfVo();
      clfVo.setBczt(ribsVo.getBxzt());
      clfMapper.updateByExampleSelective(clfVo,example);
    }else if("2".equals(bxlx)){
      Example example = new Example(JtfVo.class);
      Example.Criteria criteria = example.createCriteria();
      criteria.andEqualTo("bxdh",bxdh);
      JtfVo jtfVo = new JtfVo();
      jtfVo.setBczt(ribsVo.getBxzt());
      jtfMapper.updateByExampleSelective(jtfVo,example);
    }else if("3".equals(bxlx)){
      Example example = new Example(CyfVo.class);
      Example.Criteria criteria = example.createCriteria();
      criteria.andEqualTo("bxdh",bxdh);
      CyfVo cyfVo = new CyfVo();
      cyfVo.setBczt(ribsVo.getBxzt());
      cyfMapper.updateByExampleSelective(cyfVo,example);
    }else if("5".equals(bxlx)){
      Example example = new Example(QtVo.class);
      Example.Criteria criteria = example.createCriteria();
      criteria.andEqualTo("bxdh",bxdh);
      QtVo qtVo = new QtVo();
      qtVo.setBczt(ribsVo.getBxzt());
      qtfyMapper.updateByExampleSelective(qtVo,example);
    }
  }

  public void insertHistory(RibsVo ribsVo,String roleId,String userId){
    String id = UUIDUtils.generateShortUuid();
    //插入历史表
    HistoryVo historyVo = new HistoryVo();
    historyVo.setId(id);
    historyVo.setBxdh(ribsVo.getBxdh());
    historyVo.setBxje(ribsVo.getFyhj());
    historyVo.setBxsy(ribsVo.getBxsy());
    historyVo.setBz(ribsVo.getBz());
    historyVo.setSpyj(ribsVo.getYj());
    historyVo.setBxzt(ribsVo.getBxzt());
    historyVo.setStaffId(ribsVo.getStaffId());
    historyVo.setTp(ribsVo.getTp());
    historyVo.setRoleId(roleId);
    historyVo.setCrtUser(userId);
    historyVo.setCrtTime(new Date());
    historyVo.setUpdUser(userId);
    historyVo.setUpdTime(new Date());
    historyVo.setSprId(userId);

    historyMapper.insertSelective(historyVo);
  }

  public void deleteHistory(HistoryVo historyVo){
    historyMapper.delete(historyVo);
  }

  public List<HistoryVo> historyQuery(HistoryVo historyVo){
    return historyMapper.historyQuery(historyVo);
  }

  public void sendWxMsg(RibsVo ribsVo,String type,String userId,String staffId){

    Map<String,Object> staff = new HashMap();
    staff.put("id",userId);
    TableResultResponse staffInfo = staffFeign.getStaffInfo(staff);
    List<Map> staffInfos = staffInfo.getResult().getData();
    String wxUserId = staffInfos.get(0).get("qyhid").toString();

    Map<String,Object> staffApprove = new HashMap();
    staffApprove.put("id",staffId);
    TableResultResponse staffApproveInfo = staffFeign.getStaffInfo(staffApprove);
    List<Map> staffApproveInfos = staffApproveInfo.getResult().getData();
    String approveName = staffApproveInfos.get(0).get("name").toString();

    String bxzt = ribsVo.getBxzt();
    String je = ribsVo.getFyhj();
    String content = "";
    String accessToken = wechatBiz.getAccessToken("xx").getAccessToken();
    String bxztName = "";

    if("3".equals(bxzt)){
      bxztName = "已初审";
    }else if("4".equals(bxzt)){
      bxztName = "已复审";
    }else if("6".equals(bxzt)){
      bxztName = "已复核";
    }
    if("0".equals(type)){
      content = "您申请的报销费用(单号："+ ribsVo.getBxdh() +")已被 "+ approveName +" 驳回，驳回原因：\"" + ribsVo.getYj() + "\"，详情可登录企业微信-网上报销进行查看。";
    } else if("1".equals(type)) {
      content = "您申请的报销费用(单号："+ ribsVo.getBxdh() +")"+ bxztName +",审批人"+ approveName +"，报销金额为"+ je +"元，详情可登录企业微信-网上报销进行查看。";
    } else if("7".equals(bxzt)){
      content = "您申请的报销费用(单号："+ ribsVo.getBxdh() +")已打款，打款金额为"+ je +"元，请核实，如有问题，可与部门负责人沟通。";
    }
    wechatBiz.sendMsg(accessToken,wxUserId,"","text",content);

  }

  public String checkRole(String bxztBefore){
    String roleId = "";
    //之前状态为已提交的角色为部门负责人，已初审角色为总经理，已复审角色为会计，已复核角色为财务总监
    if("2".equals(bxztBefore)){
      roleId = "1";
    /*}else if("3".equals(bxztBefore)){
      roleId = "2";*/
    }else if("4".equals(bxztBefore)){
      roleId = "3";
    }else if("6".equals(bxztBefore)){
      roleId = "4";
    }
    return roleId;
  }
}
